package com.tgpms.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FTPUtil {


	/**
	 * 上传
	 *
	 * @param hostname ip或域名地址
	 * @param port  端口
	 * @param username 用户名
	 * @param password 密码
	 * @param workingPath 服务器的工作目
	 * @param inputStream 要上传文件的输入流
	 * @param saveName    设置上传之后的文件名
	 * @return
	 */
	public static boolean upload(String hostname, int port, String username, String password, 
			String workingPath, InputStream inputStream, String saveName) {
		boolean flag = false;
		FTPClient ftpClient = new FTPClient();
		//1 测试连接
		if (connect(ftpClient, hostname, port, username, password)) {
			try {
				//2 检查工作目录是否存在
				if (ftpClient.changeWorkingDirectory(workingPath)) {
					// 3 检查是否上传成功
					if (storeFile(ftpClient, saveName, inputStream)) {
						flag = true;
						disconnect(ftpClient);
					}
				}
			} catch (IOException e) {
				System.out.println("工作目录不存在");
				e.printStackTrace();
				disconnect(ftpClient);
			}
		}
		return flag;
	}


	/** * 下载文件 *
	 * @param hostname FTP服务器地址 *
	 * @param port FTP服务器端口号 *
	 * @param username FTP登录帐号 *
	 * @param password FTP登录密码 *
	 * @param pathname FTP服务器文件目录 *
	 * @param filename 文件名称 *
	 * @return */
	public static boolean downloadFile(String hostname, int port, String username, String password,
			String pathname, String filename,String localPath){
		boolean flag = false; 
		OutputStream os=null;
		FTPClient ftpClient = new FTPClient();
		try { 
			System.out.println("开始下载文件");
			if(connect(ftpClient, hostname, port, username, password)) {
				//切换FTP目录 
				ftpClient.changeWorkingDirectory(pathname); 
				FTPFile[] ftpFiles = ftpClient.listFiles(); 
				for(FTPFile file : ftpFiles){ 
					if(filename.equalsIgnoreCase(file.getName())){
						File localFile;
						if (StringUtils.isBlank(localPath)){
							localFile = new File("/" + file.getName());
						} else {
							localFile = new File(localPath + File.separator + file.getName());
						}
						os = new FileOutputStream(localFile);
						ftpClient.retrieveFile(file.getName(), os); 
						os.close(); 
					} 
				} 
				ftpClient.logout(); 
				flag = true; 
				System.out.println("下载文件成功");
			}
		} catch (Exception e) { 
			System.out.println("下载文件失败");
			e.printStackTrace(); 
		} finally{ 
			if(ftpClient.isConnected()){ 
				try{
					ftpClient.disconnect();
				}catch(IOException e){
					e.printStackTrace();
				}
			} 
			if(null != os){
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				} 
			} 
		} 
		return flag; 
	}
	
	/** * 删除文件 * 
	 * @param pathname FTP服务器文件目录 * 
	 * @param filename 文件名称 *  
	 * @return */
	public static boolean deleteFile(String hostname, int port, String username, String password,
			String pathname, String filename){ 
		boolean flag = false; 
		FTPClient ftpClient = new FTPClient();
		try { 
			System.out.println("开始删除文件");
			if(connect(ftpClient, hostname, port, username, password)) {
				//切换FTP目录 
				ftpClient.changeWorkingDirectory(pathname); 
				ftpClient.dele(filename); 
                ftpClient.logout();
                flag = true; 
                System.out.println("删除文件成功");
			}
		} catch (Exception e) { 
			System.out.println("删除文件失败");
			e.printStackTrace(); 
		} finally{ 
			if(ftpClient.isConnected()){ 
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            } 
		} 
		return flag; 
	}


	/**
	 * 断开连接
	 *
	 * @param ftpClient
	 * @throws Exception
	 */
	public static void disconnect(FTPClient ftpClient) {
		if (ftpClient.isConnected()) {
			try {
				ftpClient.disconnect();
				System.out.println("已关闭连接");
			} catch (IOException e) {
				System.out.println("没有关闭连接");
				e.printStackTrace();
			}
		}
	}

	/**
	 * 测试是否能连接
	 *
	 * @param ftpClient
	 * @param hostname  ip或域名地址
	 * @param port      端口
	 * @param username  用户名
	 * @param password  密码
	 * @return 返回真则能连接
	 */
	public static boolean connect(FTPClient ftpClient, String hostname, int port, String username, String password) {
		boolean flag = false;
		try {
			//ftp初始化的一些参数
			ftpClient.connect(hostname, port);
			ftpClient.enterLocalPassiveMode();
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftpClient.setControlEncoding("UTF-8");
			if (ftpClient.login(username, password)) {
				System.out.println("连接ftp成功");
				flag = true;
			} else {
				System.out.println("连接ftp失败，可能用户名或密码错误");
				try {
					disconnect(ftpClient);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			System.out.println("连接失败，可能ip或端口错误");
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * 上传文件
	 *
	 * @param ftpClient
	 * @param saveName        全路径。如/home/public/a.txt
	 * @param fileInputStream 要上传的文件流
	 * @return
	 */
	private static boolean storeFile(FTPClient ftpClient, String saveName, InputStream fileInputStream) {
		boolean flag = false;
		try {
			ftpClient.setControlEncoding("UTF-8"); // 中文支持  
	        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);  
	        ftpClient.enterLocalPassiveMode();
			if (ftpClient.storeFile(saveName, fileInputStream)) {
				flag = true;
				System.out.println("上传成功");
				disconnect(ftpClient);
			}
		} catch (IOException e) {
			System.out.println("上传失败");
			disconnect(ftpClient);
			e.printStackTrace();
		}
		return flag;
	}



	/** * 下载文件 *
	 * @param hostname FTP服务器地址 *
	 * @param port FTP服务器端口号 *
	 * @param username FTP登录帐号 *
	 * @param password FTP登录密码 *
	 * @param pathname FTP服务器文件目录 *
	 * @param filename 文件名称 *
	 * @return */
	public static InputStream downloadFileForIn(String hostname, int port, String username,
			String password, String pathname, String filename){
		FTPClient ftpClient = new FTPClient();
		InputStream in=null;
		try {
			System.out.println("开始下载文件");
			if(connect(ftpClient, hostname, port, username, password)) {
				//验证FTP服务器是否登录成功
				int replyCode = ftpClient.getReplyCode();
				if(!FTPReply.isPositiveCompletion(replyCode)){
					ftpClient.disconnect();
	                throw new IOException("failed to connect to the FTP Server");
				}
				//切换FTP目录
				ftpClient.changeWorkingDirectory(pathname);
				// ftp文件获取文件
	            in=ftpClient.retrieveFileStream(filename);
	            System.out.println("下载文件成功");
				return in;
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("下载文件失败");
		} finally{
			disconnect(ftpClient);
		} 
		return in;
	}
	
//	public static void main(String[] args) throws IOException {
//		InputStream input=null;
//		input = downloadFileForIn("10.37.10.105", 21, "ftp_xui", "XiFpt#0317", "/arch_tgpms/sthb/tzgl/qqgl/", "qqgl20200107094246374.txt");
//		int index;
//        byte[] bytes = new byte[1024];
//        FileOutputStream downloadFile = new FileOutputStream("J:\\test\\1.txt");
//        while ((index = input.read(bytes)) != -1) {
//            downloadFile.write(bytes, 0, index);
//            downloadFile.flush();
//        }
//        input.close();
//        downloadFile.close();
//	}
}
